﻿//------------------------------------------------------------------------------
//  
//------------------------------------------------------------------------------
#region Imported Namespaces
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;

using SSRS;
using PHSRAG.Insight21.Reports;
using PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.SearchContext;
using Transactions = PHSRAG.Insight21.Purchasing.Transactions;
using POAPSummaries = PHSRAG.Insight21.Purchasing.POAPSummaries;
using POAPOrderDetails = PHSRAG.Insight21.Purchasing.POAPOrderDetails;
using PHSRAG.Insight21.Agreements;

#endregion

namespace PHSRAG.Insight21.Common.Reports {

    
    public class sqlTransactionReport : sqlReport
    {

        // Account Type Column Name, needed in download to excel
        private Transactions transactionInfo = null;
        private string  incomingFundNumber;
        private string activeModule;
        private string FundNumber;
        bool IsDetail;
        bool IsOrderDetail;

        private const string SearchCriteriaVersionKey = "SearchCriteriaVersion_12B90EAE-E704-444a-8733-800F3F39866C";
        private const string SearchCriteriaLevelKey = "SearchCriteriaLevel_12B90EAE-E704-444a-8733-800F3F39866C";
        private const string ActiveModuleKey = "ActiveModule_12B90EAE-E704-444a-8733-800F3F39866C";
        private static string IncomingFundNumberKey = "IncomingFundNumberKey_CE3ACE4F-5583-4e65-A646-5170B8F97606";
		
        public sqlTransactionReport(string pageUrl)
            : base(pageUrl)
        {
            doHashtable = true;
            activeModule = searchContext.CurrentModule;

            Hashtable h = pageCachePolicy.GetCachedObject(Keys.TransactionDetailsPageKey) as Hashtable;
            FundNumber = (h == null || h[IncomingFundNumberKey] == null) ? string.Empty : (string)h[IncomingFundNumberKey];
            IsDetail = FundNumber != string.Empty;

            IsOrderDetail = Convert.ToInt32(searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.SelectOrderViewKey]) == (int)Purchasing.Enumerations.OrderView.OrderDetails;

            doCustomExcelReport = true;
            pDataSource.bLoadParameter = false;
            pRecordCount.bLoadParameter = false;
        }
        
        public override string ReportName {
            get {
                string transReptName = IsDetail ? (IsOrderDetail ? "Agmt_TransDetailPOAPOrderDetailReport" : "Agmt_TransDetailPOAPOrderSummaryReport") : (IsOrderDetail ? "Agmt_TransSummaryPOAPOrderDetailReport" : "Agmt_TransSummaryPOAPOrderSummaryReport");
                return rptFormat == "Excel" ? transReptName + "Excel" : transReptName;
            }
          
        }

        public override Hashtable setParameterHTable(ref string rptName)
        {
            reportTitle = activeModule== "Purchasing"? "PO/AP Summary":( IsDetail ? "Transaction Details" : "Transactions Overview");

            rptName = ReportName;

            if (IsDetail)
            {
                pDataSource.bLoadParameter = true;
                pRecordCount.bLoadParameter = true;

                DataSet ds = new DataSet();

                Purchasing.Transactions transactions = PeopleSoftTransaction;
                DataTable dt = transactions.GetDataContainer().Tables[Purchasing.Constants.OriginalDataTableName];

                // project header is for agreement module
                ProjectHeader projectHeaderLoader = cachePolicy.GetCachedObject(ProjectHeader.CacheKey) as ProjectHeader;
                ds = projectHeaderLoader.GetDataContainer().Copy();

                ds.Tables.Add(dt.Copy());

                StringWriter sw = new StringWriter();
                //dt.WriteXml(sw, XmlWriteMode.WriteSchema);
                ds.WriteXml(sw, XmlWriteMode.WriteSchema);
                sXMLData = sw.ToString();
                //ds = null;

                reportResultCount = transactions.Count.ToString();

            }

            else
            {
                int accessBitMask;
                bool ignoreFundStatus = false;
                bool ignoreAgreementStatus = false;
                accessBitMask = (int)Security.Enumerations.AccessRightBit.ViewFinancialInformation
                            + (int)Security.Enumerations.AccessRightBit.ViewPendingAgreements;

                if (IsOrderDetail)
                {
                    transactionInfo =
                        Policy.ResultsCache.GetObject(cachePolicy, POAPOrderDetails.CacheKey) as Transactions;
                }
                else
                {
                    transactionInfo =
                        Policy.ResultsCache.GetObject(cachePolicy, POAPSummaries.CacheKey) as Transactions;
                }

                transactionInfo.Load(
                    Utility.DataAccess.ConnectionString, Session.SessionID
                    , searchCriteria, IncomingFundNumber, accessBitMask
                    , searchContext.CurrentModule, ignoreFundStatus, ignoreAgreementStatus);

                string userid = userContext.DomainUserId.ToString();
                string usersessionid = Session.SessionID;
                htParameter.Add("domainUserId", userid);
                htParameter.Add("sessionid", usersessionid);

            }

            reportCriteria = loadCriteria(searchCriteria);

            return base.setParameterHTable(ref rptName);
        }

        protected override string loadCriteria(SearchCriteria searchCriteria)
        {
            //return searchCriteria.ToString();
            DateTime SalaryAsOfDate = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["salaryAsOfDate"];
            DateTime glPostAsOfDate = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["glPostAsOfDate"];
            DateTime POAPAsOfDate = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["poapAsOfDate"];

            return searchCriteria.ToString(";") + string.Format(
                "{0}{1}"
                , "Last GL Post|" + glPostAsOfDate.ToShortDateString() + ";"
                , "Last PO/AP Post|" + POAPAsOfDate.ToShortDateString() + ";"
                //, "Last Salary Post|" + SalaryAsOfDate.ToShortDateString() + ";"
            );
        }

        public Transactions PeopleSoftTransaction
        {
            get
            {
                int scVersion = searchCriteria.Version;
                int accessBitMask;
                bool ignoreFundStatus = false;
                bool ignoreAgreementStatus = false;
                SearchCriteria.Level scLevel = searchContext.CurrentLevel;

                if ((SearchCriteriaVersion == scVersion) && (scVersion != Purchasing.Constants.SearchVersionWhenCriteriaNotSet)
                    && scLevel == SearchCriteriaLevel)
                {
                    if (IsOrderDetail)
                    {
                        transactionInfo =
                            Policy.ResultsCache.GetObject(cachePolicy, POAPOrderDetails.CacheKey) as Transactions;
                    }
                    else
                    {
                        transactionInfo =
                            Policy.ResultsCache.GetObject(cachePolicy, POAPSummaries.CacheKey) as Transactions;
                    }
                        
                }

                if (transactionInfo == null)
                {
                    //if (IsDetail)
                    //    transactionInfo = new POAPOrderDetails();
                    //else
                    transactionInfo = new POAPSummaries();

                    string currentModule = searchContext.CurrentModule;

                    if (currentModule == InsightUtilities.Constants.Modules.Purchasing)
                    {
                        ignoreAgreementStatus = true;
                        ignoreFundStatus = true;
                        accessBitMask = (int)Security.Enumerations.AccessRightBit.ViewPeoplesoftInformation;
                    }
                    else
                    {
                        accessBitMask = (int)Security.Enumerations.AccessRightBit.ViewFinancialInformation
                            + (int)Security.Enumerations.AccessRightBit.ViewPendingAgreements;

                        //if the fund status isn't is search criteria ignore it
                        if (searchCriteria[InsightUtilities.Constants.FundStatusIDKey] == null)
                            ignoreFundStatus = true;


                    }

                    transactionInfo.Load(
                        Utility.DataAccess.ConnectionString, Session.SessionID
                        , searchCriteria, IncomingFundNumber, accessBitMask
                        , searchContext.CurrentModule, ignoreFundStatus, ignoreAgreementStatus);


                    SearchCriteriaVersion = scVersion;
                    SearchCriteriaLevel = scLevel;
                    //Policy.ResultsCache.SetObject(cachePolicy, POAPSummaries.CacheKey, transactionSummaries);
                }
                return transactionInfo;
            }
        }

        public int SearchCriteriaVersion
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(String.Format("{0}_{1}", activeModule, SearchCriteriaVersionKey)) as Hashtable;
                return (h == null || h[SearchCriteriaVersionKey] == null) ? Purchasing.Constants.SearchVersionWhenCriteriaNotSet : (int)h[SearchCriteriaVersionKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(String.Format("{0}_{1}", activeModule, SearchCriteriaVersionKey)) as Hashtable;
                if (h == null)
                    h = new Hashtable();
                h[SearchCriteriaVersionKey] = value;
                pageCachePolicy.Cache(String.Format("{0}_{1}", activeModule, SearchCriteriaVersionKey), h);
            }
        }

        public SearchCriteria.Level SearchCriteriaLevel
        {
            get
            {
                object o = pageCachePolicy.GetCachedObject(String.Format("{0}_{1}", activeModule, SearchCriteriaLevelKey));
                return (o == null) ? SearchCriteria.Level.Summary : (SearchCriteria.Level)Enum.Parse(typeof(SearchCriteria.Level), o.ToString());
            }
            set
            {
                pageCachePolicy.Cache(String.Format("{0}_{1}", activeModule, SearchCriteriaLevelKey), value);
            }
        }

        public string IncomingFundNumber
		{
			get 
			{
				return incomingFundNumber;
			}
			set
			{
				incomingFundNumber = value;
			}
		}

    }
}
